<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { getAll, remove, getCommontByUserName, getCommontById } from '../../api/commont'
import dayjs from 'dayjs'

const tableData = ref<any>([])
const getCommontAll = async () => {
  const res = await getAll()
  tableData.value = res.data.map((item) => {
    return {
      ...item,
      createDate: dayjs(item.createDate).format('YYYY-MM-DD'),
      username: item.user.username,
      articel: item.articel.title
    }
  })
}

const deleteCommont = async (index: number, row: ArticelModel) => {
  console.log(row, index)
  await remove(row.id)
  await getCommontAll()
}

const username = ref('')
const findCommontByUser = async () => {
  const res = await getCommontByUserName(username.value)
  tableData.value = res.data.map((item) => {
    return {
      ...item,
      createDate: dayjs(item.createDate).format('YYYY-MM-DD'),
      username: item.user.username,
      articel: item.articel.title
    }
  })
  username.value = ''
}

const dialogVisible = ref(false)
const content = ref('')
const findOneCommont = async (index: number, row: ArticelModel) => {
  console.log(row, index)
  const res = await getCommontById(row.id)
  dialogVisible.value = true
  content.value = res.data.content
}

onMounted(() => {
  getCommontAll()
})
</script>

<template>
  <div class="mt-4 p-5">
    <el-input v-model="username" style="max-width: 600px" placeholder="请输入用户名" class="input-with-select">
      <template #append>
        <el-button type="primary" @click="findCommontByUser" :icon="Search" />
      </template>
    </el-input>
    <el-button class="ml-4" @click="getCommontAll">重置</el-button>
  </div>

  <div class="table p-5 w-full">
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="createDate" label="创建日期" width="180" />
      <el-table-column prop="username" label="用户名" width="180" />
      <el-table-column prop="articel" label="关联文章" width="180" />
      <el-table-column prop="content" label="内容" />

      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button link type="danger" size="small" @click="deleteCommont(scope.$index, scope.row)">删除</el-button>
          <el-button link type="primary" size="small" @click="findOneCommont(scope.$index, scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="评论详情" width="500">
      <span>{{ content }}</span>

    </el-dialog>
  </div>
</template>
